package com.carey.blog.action.impl;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.carey.blog.framework.latke.action.AbstractAction;
import com.carey.blog.framework.latke.action.ActionException;
import com.carey.blog.framework.latke.model.Role;
import com.carey.blog.framework.latke.model.User;
import com.carey.blog.framework.latke.util.Strings;
import com.carey.blog.model.Common;
import com.carey.blog.util.Users;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Checks whether if a user logged in.
 * 
 */
public final class CheckLoggedInAction extends AbstractAction {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(CheckLoggedInAction.class.getName());
	/**
	 * User utilities.
	 */
	private Users userUtils = Users.getInstance();
	/**
	 * User service.
	 */
	private UserService userService = UserServiceFactory.getUserService();

	@Override
	protected Map<?, ?> doFreeMarkerAction(
			final freemarker.template.Template template,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	protected JSONObject doAjaxAction(final JSONObject data,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		final JSONObject currentUser = userUtils.getCurrentUser();
		final JSONObject ret = new JSONObject();

		try {
			ret.put(Common.IS_LOGGED_IN, false);

			if (null == currentUser) {
				if (userService.isUserLoggedIn() && userService.isUserAdmin()) {
					// Only should happen with the following cases:
					// 1. Init Blog
					// Because of there is no any user in datastore before init
					// Solo
					// although the administrator has been logged in for init
					// 2. The collaborate administrator
					ret.put(Common.IS_LOGGED_IN, true);
					ret.put(Common.IS_ADMIN, true);
					final com.google.appengine.api.users.User admin = userService
							.getCurrentUser();
					ret.put(User.USER_NAME, admin.getNickname());
				}

				ret.put(Common.LOGIN_URL,
						userService.createLoginURL("/admin-index.do"));

				return ret;
			}

			ret.put(Common.IS_LOGGED_IN, true);
			ret.put(Common.LOGOUT_URL, userService.createLogoutURL("/"));
			ret.put(Common.IS_ADMIN, Role.ADMIN_ROLE.equals(currentUser
					.getString(User.USER_ROLE)));

			String userName = currentUser.getString(User.USER_NAME);
			if (Strings.isEmptyOrNull(userName)) {
				// The administrators may be added via GAE Admin Console
				// Permissions
				userName = userService.getCurrentUser().getNickname();
				ret.put(Common.IS_ADMIN, true);
			}
			ret.put(User.USER_NAME, userName);

			return ret;
		} catch (final JSONException e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);

			return ret;
		}
	}
}
